from django.http import JsonResponse
from django.shortcuts import render
from django.db.models import Q

# Create your views here.
from elasticsearch import Elasticsearch
from rest_framework.response import Response
from rest_framework.views import APIView

from car import models, ser
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
import random

# Create your views here.
es = Elasticsearch("http://localhost:9200/")


class DataView(APIView):
    def get(self, request):
        data = request.query_params.get('data')
        # page = int(request.query_params.get('page'))
        if data:
            res = es.search(index="car", body={
                "query": {
                    "match": {
                        "name": data
                    }
                },
                # "from": 0,
                # "size": 3,
            })
        else:
            res = es.search(index="car", body={
                "query": {
                    "match_all": {}
                },
                # "from": (page - 1) * 3,
                # "size": 3,
            })
        return Response({'code': 200, 'data': res})

    def post(self, request):
        car = models.Car.objects.filter(parent__isnull=False)
        carser = ser.CarSerializer(car, many=True)
        # 这里通过访问序列化器实例的.data属性获取可迭代的序列化数据（通常是字典形式的列表）
        for serialized_car in carser.data:
            es.index(index='car', body={
                'id': serialized_car['id'],
                'name': serialized_car['name'],
                "parent": serialized_car['parent'],
                'desc': serialized_car['desc'],
                'img': serialized_car['img'],
                'price': serialized_car['price'],
                'num': serialized_car['num'],
                'user': serialized_car['user'],
            })
        return Response({'code': 200, 'data': 'ok'})


class CarView(APIView):
    def get(self, request):
        data = models.Car.objects.filter(parent__isnull=False)
        res = ser.CarSerializer(data, many=True)
        print(type(res))
        return Response({'code': 200, 'data': res.data})


class HotCarView(APIView):
    def get(self, request):
        user_id = request.query_params.get('user_id')
        parent_id = models.Car.objects.filter(user_id=user_id).values('parent').distinct()
        son = models.Car.objects.filter(~Q(user_id=user_id), parent__in=parent_id, )
        res = ser.HotCarSerializer(son, many=True)
        return Response({'code': 200, 'data': res.data})


class TestWebsocket(APIView):
    def get(self, request):
        car = models.Car.objects.filter(parent__isnull=False)
        datalist = []
        valuelist = []
        for i in car:
            datalist.append(i.name)
            valuelist.append(i.price)
        list1 = {"datalist": datalist,
                 "valuelist": [random.randint(10, 80), random.randint(10, 80), random.randint(10, 80), random.randint(10, 80)]}

        channel_layer = get_channel_layer()

        async_to_sync(channel_layer.group_send)(
            '1',  # 房间组名
            {
                'type': 'send_to_chrome',  # 消费者中处理的函数
                'data': list1
            }
        )
        return JsonResponse({"code": 200, "msg": "更新数据成功"})
